import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class DownLoadApk{

  DownLoadApk(_init());

  String fileName = '';
  String _localPath = '';
  String downloadId;
  ReceivePort _port = ReceivePort();
  
  ///初始化
  Future<void> _init() async {
    await FlutterDownloader.initialize();
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');

    _port.listen((dynamic data) {
      print('UI Isolate Callback: $data');
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];

      print("状态111: $status");
      print("进度111: $progress");
      print("id == downloadId: ${id == downloadId}");
      if (progress == 100) {
        print('okkookokokok........   $_localPath');
        Fluttertoast.showToast(
          msg: 'Download complete',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
        // OpenFile.open("$_localPath/app-release-${versionBean.versionCode}.apk");
        OpenFile.open("$_localPath/$fileName");
      }
    });
    //下载回调
    FlutterDownloader.registerCallback(downloadCallback);
    //保存目录
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    //判断目录是否存在  不存在则创建
    if (!hasExisted) {
      savedDir.create();
    }
  }

  ///回调
  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    // print('背景分离回调: 任务id ($id)  \n状态 ($status)  \n进度 ($progress)');
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  //下载apk
  downloadApk(String url) async {
    // await FlutterDownloader.initialize();
    final directory = await getExternalStorageDirectory();

    final taskId = await FlutterDownloader.enqueue(
      url: '$url',
      savedDir: directory.path,
      showNotification: true,
      openFileFromNotification: true,
    );
    // showProgressDialog();
    downloadId = taskId;
  }

  // 检查权限
  Future<bool> _checkPermission() async {
    // if (Theme.of(context).platform == TargetPlatform.android) {
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }
}